<?php

namespace app\server;

use \think\facade\Db;
use think\facade\Request;
use think\facade\Cache;
use think\facade\Queue;

class CallServer
{
    public function toCall($id, $clickId, $event = 'active')
    {
        $data = [
            'event_type' => $event,
            'context' => [
                'ad' => [
                    'callback' => $clickId
                ]
            ],
            'timestamp' => time()
        ];
        $url = 'https://analytics.oceanengine.com/api/v2/conversion';
        $response = curlData($url, json_encode($data), 'POST', '', []);
        $response = json_decode($response, true);
        $status = 2;
        $message = '';
        $code = '-1';
        if (isset($response['code'])) {
            if ($response['code'] == 0) {
//                if(!empty($logId)){
//                    $ipLogTable = getMonthTable('app_ip_logs');
//                    Db::table($ipLogTable)->where(['id'=>$logId])->inc('call_back', 1)->update();
//                }
                $status = 1;
            } else {
                $status = 2;
            }
            $message = $response['message'];
            $code = $response['code'];
        }
        $callTable = getMonthTable('app_call');
        edit($callTable, ['id' => $id], ['status' => $status, 'code' => $code, 'message' => $message]);
    }

    /**
     * 快手回传
     */
    public function ksCall($id, $call)
    {
        $status = 2;
        $message = '';
        $code = '-1';

        $callArr = json_decode($call,true);
        if(!empty($callArr['callback'])){
            $eventType = $callArr['event_type'];
            $eventTime = $callArr['event_time'];
            $url = 'http://ad.partner.gifshow.com/track/activate?event_type=' . $eventType . '&event_time=' . $eventTime . '&callback=' . $callArr['callback'];
            $response = curlData($url, [], 'GET', '', []);
            $response = json_decode($response, true);
            if (isset($response['result'])) {
                if ($response['result'] == 1) {
                    $status = 1;
                } else {
                    $status = 2;
                    $message = $response['error_msg'];
                }
                $code = $response['result'];
            }
        }else{
            $status = 2;
            $message = '缺少callback参数';
        }
        $callTable = getMonthTable('app_call');
        edit($callTable, ['id' => $id], ['status' => $status, 'code' => $code, 'message' => $message]);
    }

    /**
     * oppo回传
     */
    public function oppoCall($id, $addData)
    {
        $oppoConfig = config('seting.oppo_ad_config');
        $status = 2;
        $message = '';
        $code = '-1';
        $intRand = mt_rand(1, 100);
        if ($intRand <= 5) {
            $now = time() * 1000;
            $url = 'https://api.ads.heytapmobi.com/api/uploadActiveData';

            $imei = $addData['click_id'];
            $postData = [
                'adId' => $addData['adid'],
                'clientIp' => $addData['clientIp'],
                'dataType' => 19,
                'ascribeType' => 1,
                'channel' => 1,
                'type' => 1,
                'imei' => openssl_encrypt($imei, 'AES-128-ECB', base64_decode($oppoConfig['Base64Key']), 0, ''),
                'pkg' => $addData['pkg'],
                'timestamp' => $now
            ];
            $postJson = json_encode($postData);
            $salt = $oppoConfig['salt'];
            $signature = md5($postJson . $now . $salt);
            $header = [
                'Content-Type: application/json',
                'Content-Length: ' . strlen(json_encode($postData)),
                'signature:' . $signature,
                'timestamp: ' . $now,
            ];
            $response = http_post_json($url, $postData, $header);
            $response = json_decode($response, true);

            if (isset($response['ret'])) {
                if ($response['ret'] == 0) {
                    $status = 1;
                    $message = '成功';
                } else {
                    $status = 2;
                    $message = $response['msg'];
                }
                $code = $response['ret'];
            }
        } else {
            $code = $intRand;
            $message = "系统不回传";
        }

        $callTable = getMonthTable('app_call');
        edit($callTable, ['id' => $id], ['status' => $status, 'code' => $code, 'message' => $message]);
    }

    /**
     * 云下回传
     */
    public function wanheCall($id, $addData)
    {

        //获取回传配置
        $CallConfig = config('seting.wanhe_ad_config');
        $currentPage = $addData['current_page'] ?? '';
        $pageArr = explode('_', $currentPage);
        if (count($pageArr) !== 2) {
            return true;
        }
        $groupConfig = $CallConfig['adGroup'];
        $groupId = $pageArr[0];
        if (!isset($groupConfig[$groupId])) {
            return true;
        }
        $appid = $groupConfig[$groupId];
        $channelGroup = $CallConfig['channelGroup'];
        if (!isset($channelGroup['wanhe' . $groupId])) {
            return true;
        }
        $channel = $channelGroup['wanhe' . $groupId];
        if (!isset($CallConfig['channel'][$channel])) {
            return true;
        }
        $platformConfig = $CallConfig['channel'][$channel];
        $url = $platformConfig['callBackUrl'];
        $mchKey = $platformConfig['mchKey'];


        $status = 2;
        $message = '';
        $code = '-1';
        $postData = [
            'app_id' => $appid,
            'mch_key' => $mchKey,
            'request_id' => $addData['click_id'],
        ];
        $header = [
            'Content-Type:application/x-www-form-urlencoded',
        ];
        $response = http_post_a($url, http_build_query($postData), $header);
        $aa['postData'] = http_build_query($postData);
        $aa['response'] = $response;
        $aa['url'] = $url;
        $response = json_decode($response, true);
        if (isset($response['code'])) {
            if ($response['code'] == 0) {
                $status = 1;
                $message = '成功';
            } else {
                $status = 2;
                $message = $response['msg'];
            }
            $code = $response['code'];
        }

        $callTable = getMonthTable('app_call');
        edit($callTable, ['id' => $id], ['status' => $status, 'code' => $code, 'message' => $message]);
    }

    /**
     * 趣头条回传
     */
    public function qttCall($id, $callUrl)
    {
        $status = 2;
        $response = curlData($callUrl, [], 'GET', '', []);
        $response = json_decode($response, true);
        if (isset($response['result'])) {
            if ($response['result'] == 1) {
                $status = 1;
            }
        }
        $callTable = getMonthTable('app_call');
        edit($callTable, ['id' => $id], ['status' => $status, 'code' => $status, 'message' => '回传成功']);
    }

    /**
     * 北京瑞尚条回传
     */
    public function rsCall($id, $callUrl, $call = '', $addData = [])
    {
        $status = 2;
        $callTable = getMonthTable('app_call');
        // 北京尚瑞暂不回传
        edit($callTable, ['id' => $id], ['status' => $status, 'code' => $status, 'message' => '暂不回传']);
//        if(empty($call)){
//            if(!empty($callUrl)){
//                $response = file_get_contents($callUrl);
//                $response = json_decode($response, true);
//                if (isset($response['code'])) {
//                    if ($response['code'] == 0) {
//                        $status = 1;
//                    }
//                }
//                edit($callTable, ['id' => $id], ['status' => $status, 'code' => $status, 'message' => '回传成功']);
//            }
//        }else{
//            $url = 'https://zh.sr-times.com/hw2.php?'.$call;
//            $response = curlData($url);
//            if($response){
//                $response = json_decode($response,true);
//                if(isset($response['resultCode']) &&  $response['resultCode'] == 0){
//                    edit($callTable, ['id' => $id], ['status' => 1, 'code' =>  $response['resultCode'], 'message' => $response['resultMessage']]);
//                }
//            }
//        }
    }

    /**
     * sigMob回传
     */
    public function sigMobCall($id, $callUrl)
    {
        $callTable = getMonthTable('app_call');
        $response = curlData($callUrl);
        edit($callTable, ['id' => $id], ['status' => 1]);

    }

    /**
     * sigMob回传
     */
    public function adsCall($callArr)
    {
        $conversionType = 'keyAction';
        $postData = [
            'conversion_type' => $conversionType,
            'content_id' => $callArr['content_id'],
            'callback' => $callArr['callback'],
            'campaign_id' => $callArr['campaign_id'],
            'conversion_time'=>time(),
            'timestamp' => time()*1000,
        ];
        $current_timestamp = intval(microtime(true) * 1000);
        $posrString = json_encode($postData);
        $signature = hash_hmac('sha256', $posrString, $callArr['secretKey']);
        $auth_header = 'Digest validTime="' . $current_timestamp . '", response="' . $signature . '"';
        $header = [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($posrString),
            'Authorization: ' . $auth_header,
            'charset: UTF-8'
        ];
        $url = 'https://ppscrowd-drcn.op.cloud.huawei.com/action-lib-track/hiad/v2/actionupload';
        $response = http_post_a($url, $posrString, $header);
        $response = json_decode($response, true);
        addDebugLog('call',['res'=>json_encode($response),'request'=>$posrString,'hap'=>json_encode($callArr)]);
        $status = 1;
        return 1;
    }

}


?>
